package com.hongawen.mybatis.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hongawen.mybatis.mapper.BatchBaseMapper;
import com.hongawen.mybatis.po.RDisMpMeasurePhaseReportD;
import com.hongawen.mybatis.service.ICustomerService;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2023年06月06日 09:28
 */
public class CustomerServiceImpl<M extends BatchBaseMapper<T>, T> extends ServiceImpl<BatchBaseMapper<T>, T> implements ICustomerService<T> {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertBatchBySlice(List<T> data, int size) {
        try {
            int totalCount = data.size();
            int idxLimit = Math.min(size, totalCount);
            List<T> dataTemp = new ArrayList<>(data);
            //保存单批提交的数据集合
            if (idxLimit == size) {
                int times = totalCount / idxLimit + 1;
                for (int i = 1; i <= times; i++) {
                    System.out.printf("第%d次分片%n", i);
                    if (totalCount >= idxLimit) {
                        List<T> temp = dataTemp.subList(0, idxLimit);
                        this.baseMapper.insertBatchSomeColumn(temp);
                        temp.clear();
                        totalCount = totalCount - idxLimit;
                    } else {
                        if (CollectionUtil.isNotEmpty(dataTemp)) {
                            this.baseMapper.insertBatchSomeColumn(dataTemp);
                        }
                    }
                }
            } else {
                this.baseMapper.insertBatchSomeColumn(dataTemp);
            }
        } catch (Exception e) {
            throw new RuntimeException("分片批量插入数据异常，异常为：" + e);
        }
    }
}
